<template>
  <el-dialog 
    :visible.sync="visible"
    :width="dialogMaximized ? '98vw' : '1200px'"
    :fullscreen="dialogMaximized"
    :show-close="true"
    class="scm-product-dialog">
    <template #title>
      <span> </span>
      <el-button
        @click="toggleDialogMax"
        style="float: right; margin-right: 0; border: none; background: none;"
        circle
        :title="dialogMaximized ? '还原' : '最大化'"
      >
        <el-icon>
          <component :is="dialogMaximized ? 'Minus' : 'FullScreen'" />
        </el-icon>
      </el-button>
   </template>

    <!-- 1. 标题栏 -->
    <div style="font-weight: bold; font-size: 22px; color: #222; text-align: center; margin-bottom: 10px;">
      选择供应商订单入库
    </div>

    <!-- 2. 标签页 -->
    <el-tabs v-model="activeTab" style="margin-bottom: 10px;">
      <el-tab-pane label="待选" name="toSelect"></el-tab-pane>
      <el-tab-pane label="已选" name="selected"></el-tab-pane>
    </el-tabs>

    <!-- 选择要显示的列 + 上传控件在同一行右对齐 -->
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
      <!-- 左侧：选择要显示的列 -->
      <el-select
        v-model="visibleColumns"
        multiple
        collapse-tags
        style="width: 350px;"
        placeholder="选择要显示的列"
      >
       <el-option
          v-for="col in planColumns"
          :key="col.prop"
          :label="col.label"
          :value="col.prop"
        />
      </el-select>

      <!-- 右侧：上传控件 -->
      <div style="display: flex; align-items: center;">
        <span v-if="importFileName" style="margin-right: 10px; color: #666;">{{ importFileName }}</span>
        <el-upload
          :show-file-list="false"
          :auto-upload="false"
          :before-upload="handleBeforeUpload"
          :on-change="handleFileChange"
          accept=".xls,.xlsx"
          style="margin-right: 10px;"
        >
          <el-button type="primary">选择文件</el-button>
        </el-upload>
        <el-button
          type="success"
          :disabled="!importFile"
          @click="handleUploadConfirm"
        >确认上传</el-button>
      </div>
    </div>


    <!-- 5. 数据表格 -->
    <el-table
      :data="displayTableData"
      border
      size="small"
      style="width: 100%; font-size: 13px;"
      v-loading="loading"
      height="350"
      :row-key="row => row.sequence"
      ref="elTable"
    >
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.plan" border size="small" style="width: 100%;"
          @selection-change="val => handlePlanSelectionChange(props.row.sequence, val)">
            <el-table-column type="selection" width="40" />
            <el-table-column
              v-for="col in planColumns.filter(c => visibleColumns.includes(c.prop))"
              :key="col.prop"
              :label="col.label"
              :prop="col.prop"
              :width="col.width"  
              align="center"
            />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="sequence" label="序列" width="80" align="center" />
      <el-table-column prop="drawingNumber" label="图号" width="120" align="center" />
      <el-table-column prop="quantity" label="数量" width="80" align="center" />
      <el-table-column prop="status" label="导入状态" width="80" align="center" />
      <el-table-column prop="unprocessedQuantity" label="没有入库数" width="120" align="center" />
      <el-table-column prop="reason" label="说明" width="700" align="center" />
  
    </el-table>

    <!-- 6. 分页控件 -->
    <div v-if="activeTab === 'toSelect'" style="display: flex; justify-content: space-between; align-items: center; margin: 16px 0 0 0;">
      <div style="color: #888;">
        已选 {{ selectedRows.length }} / 共 {{ total }} 条数据
      </div>
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    <div v-else style="color: #888; margin: 16px 0 0 0;">
      已选 {{ selectedRows.length }} 条数据
    </div>

    <!-- 7. 操作按钮区 -->
    <div slot="footer" class="dialog-footer" style="text-align: right; border-top: 1px solid #eee; padding-top: 16px; margin-top: 10px;">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="warning" style="background: orange; color: #fff; border: none;" @click="handleConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { listScmSupplierOrders, getScmSupplierOrders, delScmSupplierOrders, addScmSupplierOrders, updateScmSupplierOrders } from "@/api/scm/scmSupplierOrders";
import { listScmSupplierOrderItemsWithOrderInfo, getScmSupplierOrderItems, delScmSupplierOrderItems, addScmSupplierOrderItems, updateScmSupplierOrderItems } from "@/api/scm/scmSupplierOrderItems";
import { processXLSAndGenerateLibInPlan } from "@/api/scm/scmInventoryRequest";
export default {
  name: "ScmProductItemImportDialog",
  props: {
    visible: Boolean
  },
  data() {
    return {
      activeTab: "toSelect",
      search: "",
      loading: false,
      currentPage: 1,
      pageSize: 50,
      total: 0,
      selectedRows: [],
      selectedPlanMap: {}, // { sequence: [选中的plan数组] }
      allData: [],
      selectedMap: {}, // 用于全局保存已选项
 
      visibleColumns: [
        'itemId', 
        'mainOrderCode', 
        'scmProjectProducts.drawingNumber', 
        'scmProjectProducts.drawingVersion', 
        'scmProjectProducts.productName',
        // 'material', 
        // 'size', 
        // 'specification', 
        // 'color', 
        // 'unitPriceType', 
        'unitPrice',
        'quantity', 
        'quantityInLib', 
        'amount',
        'currentRequestInQuantity'
      ],
    dialogMaximized: false,
    importFile: null,
    importFileName: '',
    importData: [],
    planColumns: [
        { label: 'ID', prop: 'itemId' , width: 45},
        { label: '供应商订单号', prop: 'mainOrderCode', width: 180 },
        { label: '图号/型号', prop: 'scmProjectProducts.drawingNumber', width: 100},
        { label: '版本', prop: 'scmProjectProducts.drawingVersion' , width: 60},
        { label: '品名', prop: 'scmProjectProducts.productName' , width: 100},
        { label: '材质', prop: 'scmProjectProducts.material' , width: 60},
        { label: '尺寸', prop: 'size' , width: 60},
        { label: '规格', prop: 'scmProjectProducts.specification', width: 60 },
        { label: '颜色', prop: 'scmProjectProducts.color', width: 60 },
        { label: '单价类型', prop: 'unitPriceType', width: 100 },
        { label: '单价', prop: 'unitPrice', width: 100 },
        { label: '订单数量', prop: 'quantity' , width: 100},
        { label: '已入库量', prop: 'quantityInLib', width: 100 },
        { label: '金额', prop: 'amount', width: 100 },
        { label: '入库数量', prop: 'currentRequestInQuantity' },
        { label: '入库仓库ID', prop: 'warehouseId' },
        { label: '入库库位ID', prop: 'locationId' },
        // ...其它你需要展示的字段
      ],
    };
    
  },
  computed: {
    tableData() {
      // 搜索和分页
      let filtered = this.allData.filter(item =>
        !this.search ||
        (item.productName && item.productName.includes(this.search)) ||
        (item.drawingNumber && item.drawingNumber.includes(this.search)) ||
        (item.model && item.model.includes(this.search)||
        (item.mainOrderCode && item.mainOrderCode.includes(this.search)))
      );
      this.total = filtered.length;
      const start = (this.currentPage - 1) * this.pageSize;
      return filtered.slice(start, start + this.pageSize);
    },
    displayTableData() {
      // 待选tab显示tableData，已选tab显示所有已选
      if (this.activeTab === "toSelect") {
        return this.tableData;
      } else {
        return Object.values(this.selectedMap);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.currentPage = 1;
        this.fetchData();
        this.$nextTick(() => {
          if (this.activeTab === "toSelect") this.setTableSelection();
        });
      }
    },
    activeTab(val) {
      // 切换到已选时，取消表格的多选框选中状态
      if (val === "selected" && this.$refs.elTable) {
        this.$refs.elTable.clearSelection();
      }
      if (val === "toSelect" && this.$refs.elTable) {
        this.$nextTick(() => {
          this.setTableSelection();
        });
      }
    }
  },
  methods: {

    fetchData() {
      this.loading = true;
      listScmSupplierOrderItemsWithOrderInfo({ pageNum: this.currentPage, pageSize: this.pageSize, search: this.search }).then(res => {
        this.allData = res.rows || [];
        this.total = res.total || this.allData.length;
        this.loading = false;
        this.$nextTick(() => {
          if (this.activeTab === "toSelect") this.setTableSelection();
        });
        console.log(res.rows); // 检查每条数据是否有这些字段
      }).catch(() => {
        this.loading = false;
      });
    },
    setTableSelection() {
      if (this.$refs.elTable) {
        this.$refs.elTable.clearSelection();
        this.tableData.forEach(row => {
          if (this.selectedMap[row.itemId]) {
            this.$refs.elTable.toggleRowSelection(row, true);
          }
        });
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    handleAdd() {
      this.$message.info("点击了新增数据");
    },
    handleSelectionChange(val) {
      // 先把当前页所有数据从 map 里移除
      this.tableData.forEach(item => {
        if (this.selectedMap[item.itemId]) {
          delete this.selectedMap[item.itemId];
        }
      });
      // 再把当前页勾选的加进去
      val.forEach(item => {
        this.selectedMap[item.itemId] = item;
      });
      // 更新 selectedRows
      this.selectedRows = Object.values(this.selectedMap);
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchData();
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    handleCancel() {
      this.$emit("select", []);
      this.$emit("update:visible", false);
    },
    handleConfirm() {
      // 收集所有选中的plan
      console.log('selectedPlanMap:', this.selectedPlanMap);
      let selectedPlans = [];
      Object.values(this.selectedPlanMap).forEach(arr => {
        selectedPlans = selectedPlans.concat(arr);
      });
      console.log('最终选中的数据:', selectedPlans);
      this.$emit("select", selectedPlans);
      this.$emit("update:visible", false);
    },
 
    toggleDialogMax() {
      this.dialogMaximized = !this.dialogMaximized;
    },
    handleFileChange(file) {
      this.importFile = file.raw;
      this.importFileName = file.name;
    },
    handleUploadConfirm() {
      if (!this.importFile) return;
      const formData = new FormData();
      formData.append('file', this.importFile);
      this.loading = true;
      processXLSAndGenerateLibInPlan(formData).then(res => {
        // 处理为主表+子表结构
        console.log('allData:', JSON.stringify(res, null, 2));
        
        this.allData = (res.data || []).map(item => ({
          sequence: item["序列"],
          drawingNumber: item["图号"],
          quantity: item["数量"],
          status: item["status"],
          unprocessedQuantity: item["unprocessedQuantity"],
          reason: item["reason"],
          plan: item["plan"] || []
        }));
        this.total = this.allData.length;
        this.loading = false;
        this.$nextTick(() => {
          if (this.activeTab === "toSelect") this.setTableSelection();
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    handlePlanSelectionChange(sequence, val) {
      console.log('sequence:', sequence, '选中:', val);
      this.selectedPlanMap[sequence] = val;
      console.log('selectedPlanMap:', this.selectedPlanMap);
    },
    handleBeforeUpload() {
      // 可以做校验或直接 return true
      return true;
    },
          
  }
};
</script>

<style scoped>
.scm-product-dialog .el-table th,
.scm-product-dialog .el-table td {
  padding: 4px 6px !important;
  font-size: 13px;
  line-height: 1.2;
}
</style>